import './CouponCom.less'
import { HolderOutlined } from '@ant-design/icons'
import { useModel } from '@umijs/max'
import { Button, Form, Typography, App, Popconfirm, Radio, Drawer, Space, Spin, Alert } from 'antd'
import { ProTable } from '@ant-design/pro-components'
import FlipMove from 'react-flip-move'
import { useEffect, useState, forwardRef, useImperativeHandle, useRef } from 'react'
import styles from './CouponCom.less'
import dayjs from 'dayjs'

function CouponCom({}, ref) {
  const { message } = App.useApp()

  const [oldDragItem, setOldDragItem] = useState() // 当前拖拽对象
  const [newDragItem, setNewDragItem] = useState() // 拖拽交换对象
  const [isEnter, setIsEnter] = useState() // 是否拖拽进行
  const [isActive, setIsActive] = useState() // 是否拖拽

  const [couponRadioFormRef] = Form.useForm() // 优惠券选项表单
  const { couponList, setCouponList, isHideCoupon, setIsHideCoupon, DynamicPageData, goodsList, setGoodsList } =
    useModel('ActivityEditor')

  const { CouponList } = useModel('Coupon')

  const [couponDrawer, setCouponDrawer] = useState(false) // 选择优惠券抽屉
  const [couponDrawerLoading, setCouponDrawerLoading] = useState(false) // 选择优惠券抽屉 loading
  const [drawerSelectCoupon, setDrawerSelectCoupon] = useState([]) // 选择的优惠券
  const [addCouponPageSize, setAddCouponPageSize] = useState(5) //  每页数量
  const selectCouponTableRef = useRef() // 选择优惠券表格ref
  let cancelRowKeys = [] // 取消选择的项目

  // 开关优惠券抽屉
  const triggerCouponDrawer = () => {
    setCouponDrawer(!couponDrawer)
  }

  // 处理优惠券抽屉选择优惠券
  const handleDisplay = async () => {
    if (!drawerSelectCoupon.length) {
      message.warning('请最少选择一个优惠券')
      return
    }

    setCouponDrawerLoading(true)
    // 动态计算价格
    let params = {
      goodsList: goodsList.map(i => ({ id: i.id })),
      couponList: drawerSelectCoupon.map(i => ({ id: i.id }))
    }

    const res = await DynamicPageData(params)

    if (res) {
      setCouponDrawerLoading(false)
      setCouponList([...res.couponList])
      setGoodsList([...res.goodsList])

      setDrawerSelectCoupon([])
      triggerCouponDrawer()
    }
  }

  /* 拖拽开始 */
  const onDragStart = value => {
    setOldDragItem(value)
    setIsActive(value.id)
  }

  /* 拖拽进行 */
  const onDragEnter = value => {
    setIsEnter(value.id)
    setNewDragItem(value)
  }

  /* 拖拽结束 */
  const onDragEnd = () => {
    if (oldDragItem !== newDragItem) {
      const oldIndex = couponList.indexOf(oldDragItem) //获取当前对象所在数组坐标
      const newIndex = couponList.indexOf(newDragItem) //获取当前目标对象所在数组坐标
      const newArray = [...couponList]
      newArray.splice(oldIndex, 1) //删除老节点
      newArray.splice(newIndex, 0, oldDragItem) //增加新节点
      setCouponList(newArray) //保存拖拽后的数组
      setIsActive(-1) //重置状态
      setIsEnter(-1)
    }
  }

  useEffect(() => {
    document.addEventListener('dragover', function (event) {
      //阻止事件的默认行为
      event.preventDefault()
      //设置拖拽时鼠标样式
      event.dataTransfer.dropEffect = 'move'
    })
  }, [])

  // 新增
  const handleAddCoupon = () => {
    if (couponList.length >= 10) {
      message.error('最多添加10个')
      return
    }

    triggerCouponDrawer()
    if (couponList && couponList.length) {
      setDrawerSelectCoupon(couponList)
    }
  }

  // 删除
  const handleRemoveCoupon = async item => {
    const newArray = couponList.filter(v => v.id !== item.id)
    // setCouponList(newArray)

    // 重新计算价格
    let params = {
      goodsList: goodsList.map(i => ({ id: i.id })),
      couponList: newArray.map(i => ({ id: i.id }))
    }

    const res = await DynamicPageData(params)

    if (res) {
      setCouponList([...res.couponList])
      setGoodsList([...res.goodsList])
    }
  }

  // 获取提交数据
  const handleFinish = () => {
    const values = couponRadioFormRef.getFieldsValue()
    let params = {
      couponList,
      ...values
    }

    return params
    // console.log('params========', params)
  }

  // 暴露给父组件的方法
  useImperativeHandle(ref, () => ({
    handleFinish
  }))

  // 监听 form 表单值变化
  const onValuesChange = (changedValues, values) => {
    setIsHideCoupon(values)
  }

  const selectCouponColumns = [
    {
      title: '优惠券信息',
      dataIndex: 'coupon_name',
      // width: 240,
      hideInSearch: true,
      render: (text, record) => {
        return (
          <>
            <div>
              <b>{text}</b>
            </div>
            <div>券ID：{record.id}</div>
          </>
        )
      }
    },
    {
      title: '推广方式',
      dataIndex: 'show_type',
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        1: '自动推广',
        2: '私域链接'
      }
    },
    {
      title: '类型',
      dataIndex: 'deduct_type',
      width: 100,
      align: 'center',
      hideInSearch: true,
      valueEnum: {
        1: '下单立减'
      }
    },
    {
      title: '优惠内容',
      dataIndex: 'content_text',
      hideInSearch: true,
      width: 300,
      align: 'center'
    },
    {
      title: '状态',
      dataIndex: 'status_text',
      width: 120,
      hideInSearch: true,
      align: 'center',
      valueEnum: {
        未开始: {
          text: '未开始',
          status: 'Default'
        },
        进行中: {
          text: '进行中',
          status: 'Processing'
        },
        已结束: {
          text: '已结束',
          status: 'Error'
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      hideInTable: true,
      align: 'center',
      valueEnum: {
        not_start: '未开始',
        running: '进行中',
        over: '已结束'
      }
    },

    {
      title: '可用时间',
      dataIndex: 'use_start_at',
      width: 240,
      hideInSearch: true,
      align: 'center',
      render: (_, row) => (
        <>
          <div>起：{_}</div>
          <div>止：{row.use_end_at}</div>
        </>
      )
    },

    {
      title: '领取量',
      dataIndex: 'receive_num',
      width: 120,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '发放量',
      dataIndex: 'send_num',
      width: 120,
      align: 'center',
      hideInSearch: true
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 200,
      align: 'center',
      valueType: 'dateTimeRange',
      render: (_, record) => <div>{record.created_at}</div>,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d']).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },
    {
      title: '可用时间',
      dataIndex: 'use_at',
      width: 100,
      align: 'center',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: value => {
          return {
            start: dayjs(value[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
            end: dayjs(value[1]['$d']).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    }
  ]

  return (
    <div className='coupon_com'>
      <div className='coupon_title'>
        已选择优惠券{couponList.length}个<span>拖拽可排序</span>
      </div>

      <div className='coupon_list'>
        <FlipMove duration={200} easing='ease-out'>
          {couponList.map(item => (
            <div
              className={
                oldDragItem === item && isActive === item.id
                  ? 'coupon_active coupon_item'
                  : newDragItem === item && isEnter === item.id
                  ? 'coupon_enter coupon_item'
                  : 'coupon_item'
              }
              draggable={true}
              onDragStart={() => {
                onDragStart(item)
              }}
              onDragEnter={() => {
                onDragEnter(item)
              }}
              onDragEnd={() => {
                onDragEnd()
              }}
              key={item.id}
            >
              <HolderOutlined style={{ marginRight: '5px' }} />
              优惠券: {item.name}
              <Popconfirm
                title='确认删除吗?'
                onConfirm={() => handleRemoveCoupon(item)}
                okText='确认'
                cancelText='取消'
              >
                <div className='coupon_delete'>-</div>
              </Popconfirm>
            </div>
          ))}
        </FlipMove>

        <Button style={{ marginTop: '20px' }} block size='large' type='dashed' onClick={() => handleAddCoupon()}>
          选择优惠券({couponList.length}/10)
        </Button>

        <Form
          onValuesChange={onValuesChange}
          style={{ marginTop: '20px' }}
          preserve={false}
          form={couponRadioFormRef}
          name='coupon_radio_form'
          initialValues={{
            isHideCoupon
          }}
        >
          <Form.Item
            extra='当页面无可显示的优惠券时，优惠券区块将隐藏'
            name='isHideCoupon'
            label='隐藏已抢完及失效的券 : '
          >
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </div>

      {/*选择优惠券抽屉*/}
      <Drawer
        title='选择优惠券'
        placement='right'
        className={styles.coupon_drawer_wrapper}
        onClose={triggerCouponDrawer}
        open={couponDrawer}
        width={980}
        destroyOnClose
        footer={
          <div className={styles.drawer_footer}>
            <Space>
              <Button disabled={!drawerSelectCoupon.length} onClick={triggerCouponDrawer}>
                取消
              </Button>
              <Button type='primary' disabled={!drawerSelectCoupon.length} onClick={handleDisplay}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <div className='drawer_content'>
          {couponDrawerLoading && (
            <div className='drawer_loading'>
              <Spin></Spin>
              <p>数据处理中...</p>
            </div>
          )}

          <Alert message='仅可以选择自动推广的优惠券活动（最多10种），已结束的优惠券不可选择' type='info' showIcon />
          <ProTable
            search={{
              defaultCollapsed: false,
              labelWidth: 75,
              span: 6
            }}
            actionRef={selectCouponTableRef}
            tableAlertOptionRender={() => {
              return false
            }}
            rowSelection={{
              selectedRowKeys: drawerSelectCoupon.map(i => i.id),
              onChange: (keys, rows) => {
                let tempList = [...rows, ...drawerSelectCoupon.filter(i => !keys.includes(i.id))]
                if (cancelRowKeys.length) {
                  setDrawerSelectCoupon(tempList.filter(i => !cancelRowKeys.includes(i.id)))
                } else {
                  setDrawerSelectCoupon(tempList)
                }
              },

              onSelect: (record, selected) => {
                if (!selected) {
                  cancelRowKeys = [record.id]
                }
              }
            }}
            request={async params => {
              const param = {
                page: params.current,
                page_size: params.pageSize,
                shop_name: params.shop_name,
                contact_tel: params.contact_tel,
                legal_person_name: params.legal_person_name,
                status: params.status,
                created_at_start: params.start,
                created_at_end: params.end,
                show_type: 1 // 1自动推广  2私域链接
              }

              const res = await CouponList(param)
              setAddCouponPageSize(params.pageSize)
              return {
                data: res.data,
                success: true,
                total: res.total
              }
            }}
            pagination={{
              pageSize: addCouponPageSize
            }}
            options={false}
            rowKey='id'
            scroll={{ x: 'max-content' }}
            columns={selectCouponColumns}
          />
        </div>
      </Drawer>

      {/* <div>
        <Typography>
          <pre>{JSON.stringify(couponList, null, 2)}</pre>
        </Typography>
      </div> */}
    </div>
  )
}

export default forwardRef(CouponCom)
